mod esl;
mod client;

use anyhow::Result;
use clap::{Parser, Subcommand};
use client::FreeSwitchClient;
use tokio::time::Duration;
use tracing::info;

#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
    /// FreeSWITCH服务器地址
    #[arg(short, long, default_value = "127.0.0.1")]
    host: String,

    /// FreeSWITCH ESL端口
    #[arg(short, long, default_value = "8021")]
    port: u16,

    /// 认证密码
    #[arg(short = 'w', long, default_value = "ClueCon")]
    password: String,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// 拨打电话
    Call {
        /// 要拨打的电话号码
        #[arg(short, long)]
        number: String,

        /// 呼叫超时时间（秒）
        #[arg(short, long, default_value = "30")]
        timeout: u64,

        /// 监听事件的时间（秒）
        #[arg(short, long, default_value = "60")]
        listen_duration: u64,
    },
    /// 列出所有活动通道
    ListChannels,
    /// 获取FreeSWITCH状态
    Status,
    /// 监听事件
    Listen {
        /// 监听时间（秒）
        #[arg(short, long, default_value = "60")]
        duration: u64,
    },
}

#[tokio::main]
async fn main() -> Result<()> {
    // 初始化日志
    tracing_subscriber::fmt::init();

    let args = Args::parse();
    
    info!("连接到FreeSWITCH服务器: {}:{}", args.host, args.port);
    
    // 连接到FreeSWITCH
    let mut client = FreeSwitchClient::connect(&args.host, args.port).await?;
    
    // 认证
    client.authenticate(&args.password).await?;
    
    match args.command {
        Commands::Call { number, timeout, listen_duration } => {
            // 订阅事件
            client.subscribe_events().await?;
            
            // 拨打电话
            let job_uuid = client.make_call(&number, timeout).await?;
            info!("呼叫已发起，任务UUID: {}", job_uuid);
            
            // 监听事件
            let duration = Duration::from_secs(listen_duration);
            client.listen_for_events(Some(duration)).await?;
        }
        Commands::ListChannels => {
            let channels = client.list_channels().await?;
            println!("活动通道列表:");
            for (i, channel) in channels.iter().enumerate() {
                println!("{}. UUID: {}, 方向: {}, 创建时间: {}, 名称: {}", 
                    i + 1,
                    channel.get("uuid").unwrap_or(&"N/A".to_string()),
                    channel.get("direction").unwrap_or(&"N/A".to_string()),
                    channel.get("created").unwrap_or(&"N/A".to_string()),
                    channel.get("name").unwrap_or(&"N/A".to_string())
                );
            }
        }
        Commands::Status => {
            let status = client.get_status().await?;
            println!("FreeSWITCH状态:");
            println!("{}", status.to_string());
        }
        Commands::Listen { duration } => {
            // 订阅事件
            client.subscribe_events().await?;
            
            // 监听事件
            let listen_duration = Duration::from_secs(duration);
            client.listen_for_events(Some(listen_duration)).await?;
        }
    }

    Ok(())
}
